import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login.vue'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/welcome'
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      title: "登录"
    },
    component: Login
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.name !== "login" && !sessionStorage.getItem("token")) {
    //如果未登录，跳转至登录页
    router.push("/login")
  }
  if (to.name !== "login" && to.name !== "Welcome") {
    //将此页添加到标签栏
    const tags = store.state.tags
    if (!tags.map(item => item.name).includes(to.name)) {
      tags.push({
        name: to.name,
        path: to.path,
        title: to.meta && (to.meta.title || "默认")
      })
    }
  }

  //获取每个路由的meta信息，赋值给浏览器的标题属性
  window.document.title = to.meta && (to.meta.title || "默认")
  next()
})

export default router
